import React from 'react'
import PropTypes from 'prop-types'
import { observer, inject } from 'mobx-react'
import cx from 'classnames'
import Helmet from 'react-helmet'
import queryString from 'query-string'

import List from '@material-ui/core/List'
import ListItem from '@material-ui/core/ListItem'
import ListItemAvatar from '@material-ui/core/ListItemAvatar'
import ListItemText from '@material-ui/core/ListItemText'
import Tab from '@material-ui/core/Tab'
import Tabs from '@material-ui/core/Tabs'
import Avatar from '@material-ui/core/Avatar'
import CircularProgress from '@material-ui/core/CircularProgress'
import { withStyles } from '@material-ui/core/styles'

import Container from '../layout/Container'
import { topicPrimaryStyle, topicSecondaryStyle } from './styles'
import { tabs } from '../../utils/variable'
import formatDate from '../../utils/data-format'

const getTab = (tab, isTop, isGood) => {
  return isTop ? '置顶' : isGood ? '精华' : tab
}

const TopicPrimary = ({ topic, classes }) => {
  const isTop = topic.top
  const isGood = topic.good
  const classNames = cx([classes.tab, isTop ? classes.top : isGood ? classes.good : ''])
  return (
    <div className={ classes.root }>
      <span className={ classNames }>
        { getTab(tabs[topic.tab], isTop, isGood) }
      </span>
      <span>{ topic.title }</span>
    </div>
  )
}
const TopicSecondary = ({ topic, classes }) => (
  <span className={ classes.root }>
    <span className={ classes.userName }>{ topic.author.loginname }</span>
    <span>
      创建时间:
      { formatDate(topic.create_at, 'yyyy-mm-dd') }
    </span>
  </span>
)
TopicPrimary.propTypes = {
  topic: PropTypes.object.isRequired,
  classes: PropTypes.object.isRequired,
}
TopicSecondary.propTypes = {
  topic: PropTypes.object.isRequired,
  classes: PropTypes.object.isRequired,
}

const StyledTopicPrimary = withStyles(topicPrimaryStyle)(TopicPrimary)
const StyledTopicSecondary = withStyles(topicSecondaryStyle)(TopicSecondary)

@inject(stores => {
  return {
    appState: stores.appState,
    topicStore: stores.topicStore,
  }
})
@observer
class TopicList extends React.Component {
  componentDidMount() {
    this.getTopicList()
  }

  componentWillReceiveProps(nextProps) {
    const { location } = this.props

    if (nextProps.location.search !== location.search) {
      this.getTopicList(nextProps.location)
    }
  }

  getTopicList = (next) => {
    const { topicStore, location } = this.props

    next = next || location
    const query = queryString.parse(next.search)
    topicStore.fetchTopics(query.tab || 'share')
  }

  changeTab = (event, value) => {
    const { history } = this.props

    history.push({
      pathname: '/index',
      search: `?tab=${value}`,
    })
  }

  asyncBootstrap() {
    const { topicStore, location } = this.props

    const query = queryString.parse(location.search)
    return topicStore.fetchTopics(query.tab || 'share').then(() => {
      return true
    }).catch(() => {
      return false
    })
  }

  render() {
    const { topicStore, location } = this.props
    const query = queryString.parse(location.search)
    const tabValue = query.tab || 'share'

    return (
      <Container>
        <Helmet>
          <title>话题列表</title>
        </Helmet>

        <div>
          <Tabs value={ tabValue } onChange={ this.changeTab }>
            {
              Object.keys(tabs).map(item => <Tab key={ item } label={ tabs[item] } value={ item } />)
            }
          </Tabs>
        </div>

        <List style={ { backgroundColor: '#dfdfdf' } }>
          { topicStore.topics.map(topic => (
            <ListItem button key={ topic.id }>
              <ListItemAvatar>
                <Avatar src={ topic.author.avatar_url } />
              </ListItemAvatar>
              <ListItemText
                primary={ <StyledTopicPrimary topic={ topic } /> }
                secondary={ <StyledTopicSecondary topic={ topic } /> }
              />
            </ListItem>
          ))
          }
        </List>

        { topicStore.syncing
          ? (
            <div
              style={ {
                display: 'flex',
                justifyContent: 'space-around',
                padding: '40px 0',
              } }
            >
              <CircularProgress color="secondary" size={ 100 } />
            </div>
          )
          : null
        }
      </Container>
    )
  }
}

TopicList.wrappedComponent.propTypes = {
  topicStore: PropTypes.object.isRequired,
}

TopicList.propTypes = {
  location: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
}


export default TopicList
